package com.winsdom.utils;

import com.winsdom.domain.vo.FinishedTaskVO;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ExcelUtil {
    public static void exportToExcel(List<FinishedTaskVO> dataList, HttpServletResponse response) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("已抄表任务");

        // 创建表头
        String[] headers = {"生成日期", "需要数量", "已完成数量", "完成时间", "楼盘名称", "推表周期"};
        Row headerRow = sheet.createRow(0);
        for (int i=0; i<headers.length; i++) {
            headerRow.createCell(i).setCellValue(headers[i]);
        }

        // 填充数据
        int rowNum = 1;
        for (FinishedTaskVO vo : dataList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(vo.getGenerateDate().toString());
            row.createCell(1).setCellValue(vo.getNeedTotal());
            row.createCell(2).setCellValue(vo.getFinishedTotal());
            row.createCell(3).setCellValue(vo.getCompleteTime().toString());
            row.createCell(4).setCellValue(vo.getCategoryName());
            row.createCell(5).setCellValue(vo.getReadingCycle());
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=finished_tasks.xlsx");

        workbook.write(response.getOutputStream());
        workbook.close();
    }
}
